<template>
  <el-card
    style="margin: 10px 15px"
    shadow="always"
    :body-style="{ padding: '20px' }"
  >
    <el-form label-width="80px" inline size="normal">
      <el-form-item>
        <el-input
          v-model="roleName"
          placeholder="角色名称"
          size="small"
          clearable
          style="width: 200px; margin-right: 20px"
        />
      </el-form-item>

      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="selectOrClear(0)"
      >
        查询
      </el-button>
      <el-button type="default" size="small" @click="selectOrClear(1)">
        清空
      </el-button>
    </el-form>

    <div style="margin: 5px 0">
      <el-button type="primary" size="small" @click="addOrEditHandler(0, [])">
        添加
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="selectionList.length === 0"
        @click="secListDeletes"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      border
      stripe
      :data="roleList"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="70" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="roleName" label="角色名称" align="center" />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="info"
            size="small"
            icon="el-icon-user-solid"
            title="分配角色"
            @click="roleHandler(scope.row)"
          />
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit-outline"
            title="编辑角色"
            @click="addOrEditHandler(1, scope.row)"
          />
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @onConfirm="delRole(scope.row.id)"
          >
            <el-button
              slot="reference"
              style="margin-left: 10px"
              type="danger"
              size="small"
              icon="el-icon-delete"
              title="删除用户"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="prev,pager,next,jumper,sizes,total"
      background
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      :current-page.sync="currentPage"
      :total="total"
      @size-change="sizeChange"
      @current-change="currentChangeHandler"
    />
    <el-dialog
      :title="formData.id ? '编辑角色' : '添加角色'"
      :visible.sync="isDialog"
      @close="closeDialog"
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        label-width="80px"
        :validate-on-rule-change="false"
        :inline="false"
        size="normal"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" size="small" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="isDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmHandler">确定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqBatchDelRole,
  reqDelSingleRole,
  reqRoleList,
  reqAddRole,
  reqEditRole,
  reqAddOrEditRole,
} from "@/api/role";

export default {
  name: "Role",
  data() {
    return {
      roleName: "", //input双绑
      currentPage: 1,
      pageSize: 5,
      loading: false,
      roleList: [],
      total: 0,
      isDialog: false,
      selectionList: [],
      temporaryData: "",
      newRoleName: "",
      formData: {
        roleName: "",
      },
    };
  },

  mounted() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      try {
        this.loading = true;
        const result = await reqRoleList(
          this.currentPage,
          this.pageSize,
          this.roleName
        );
        this.roleList = result.items;
        this.total = result.total;
        this.loading = false;
      } catch (e) {
        this.$message.error("获取角色列表失败");
        this.loading = false;
        this.roleList = [];
      }
    },
    sizeChange(val) {
      this.pageSize = val;
      this.getRoleList();
    },
    currentChangeHandler(val) {
      this.currentPage = val;
      this.getRoleList();
    },
    //查询&清空
    selectOrClear(id) {
      if (id === 1) {
        this.roleName = "";
      }
      this.getRoleList();
    },
    addOrEditHandler(type, row) {
      this.isDialog = true;
      if (type === 1) {
        this.formData = {
          id: row.id,
          roleName: row.roleName,
        };
      }
      this.$nextTick(() => {
        this.$refs.formDataRef.clearValidate();
      });
    },
    async confirmHandler() {
      await this.$refs.formDataRef.validate(async (valid) => {
        if (valid) {
          try {
            await reqAddOrEditRole(this.formData);
            this.isDialog = false;
            await this.getRoleList();
            this.$message.success(this.formData.id ? "编辑成功" : "添加成功");
          } catch (e) {
            this.$message.error(this.formData.id ? "编辑失败" : "添加失败");
          }
        } else {
          this.$message.warning("清查看表单是否验证错误!");
        }
      });
    },

    closeDialog() {
      this.formData = {
        roleName: "",
      };
    },
    async delRole(id) {
      try {
        await reqDelSingleRole(id);
        this.getRoleList();
        this.$message.success("删除成功");
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    //批量删除部分
    //保存选中的数据
    selectionChange(secList) {
      this.selectionList = secList;
    },
    //批量删除
    secListDeletes() {
      const secId = this.selectionList.map((item) => item.id);
      this.$confirm("请问确定要进行批量删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }).then(async () => {
        try {
          await reqBatchDelRole(secId);
          this.getRoleList();
          this.$message.success("批量删除成功");
        } catch (e) {
          this.$message.error(e.message);
        }
      });
    },

    //跳转到管理页
    roleHandler(row) {
      this.$router.push({
        name: "RoleTree",
        query: {
          id: row.id,
          roleName: row.roleName,
        },
      });
    },
  },
};
</script>
